//
//  Connection.m
//  HiQ
//
//  Created by maxwell pang on 12-7-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Connection.h"

#define TAG_FIXED_LENGTH_HEADER 1
#define TAG_RESPONSE_BODY 2
#define HEADER_LENGTH sizeof(NSUInteger)

@implementation Connection
@synthesize delegate;

static Connection *sharedServerConnection;

- (id) initWithHostAddress:(NSString *)_host andPort:(NSInteger)_port
{
    socketQueue = dispatch_queue_create("socketQueue", NULL);
    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];
    
    NSError *err = nil;
    if (![socket connectToHost:_host onPort:_port error:&err]) // Asynchronous!
    {
        // If there was an error, it's likely something like "already connected" or "no delegate set"
        NSLog(@"I goofed: %@", err);
    }
    
    // Heck, while I'm at it, I might as well queue up the read for the first response.
    [socket readDataToLength:HEADER_LENGTH withTimeout:-1 tag:TAG_FIXED_LENGTH_HEADER];
    

    sharedServerConnection = self;
    return self;
}

- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"I'm connected!");
}

- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
    if (tag == TAG_FIXED_LENGTH_HEADER)
    {
        //解包获取主信息的长度
        UTF8Char * bytes = (UTF8Char *)[data bytes];
        NSUInteger bodyLength =*((NSUInteger *)bytes);
        [socket readDataToLength:bodyLength withTimeout:-1 tag:TAG_RESPONSE_BODY];
    }
    else if (tag == TAG_RESPONSE_BODY)
    {
        // Pass the response data to business logic
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.delegate dispathPacket:data];
        });
        
        // Start reading the next response
        [socket readDataToLength:HEADER_LENGTH withTimeout:-1 tag:TAG_FIXED_LENGTH_HEADER];
    }
}


- (void) sendMsg:(NSString *)msg cmd:(NSUInteger)_cmdFlag subcmd:(NSUInteger)_subCmdFlag
{
    //添加固定长度头
    NSData * msgData = [msg dataUsingEncoding:NSUTF8StringEncoding] ;
    NSUInteger length = msgData.length+16;
    NSMutableData *data = [NSMutableData dataWithBytes:&(length) length:sizeof(NSUInteger)];
    [data appendBytes:&(_cmdFlag) length:sizeof(NSUInteger)];
    [data appendBytes:&(_subCmdFlag) length:sizeof(NSUInteger)];
    [data appendData:msgData];
    
    [socket writeData: data withTimeout: -1 tag: 0];

}


//发送Data接口
//add by arvintan 12-8-1
-(void) sendData:(NSData *)_data cmd:(NSUInteger)_cmdFlag subcmd:(NSUInteger)_subCmdFlag
{
    NSUInteger length = _data.length + 16;
    NSMutableData *data = [NSMutableData dataWithBytes:&(length) length:sizeof(NSUInteger)];
    [data appendBytes:&(_cmdFlag) length:sizeof(NSUInteger)];
    [data appendBytes:&(_subCmdFlag) length:sizeof(NSUInteger)];
    [data appendData:_data];
    
    NSUInteger len = *((NSUInteger *)([data bytes]));
    NSUInteger cmd = *((NSUInteger *)([data bytes] + 8));
    NSUInteger subcmd = *((NSUInteger *)([data bytes] + 16));
    NSLog(@"len is %lu, cmd is %lu, subcmd is %lu", len, cmd, subcmd);
    [socket writeData: data withTimeout: -1 tag: 0];
    
}


+ (id) sharedServerConnection
{
    return sharedServerConnection;
}




@end
